class IDB {
  constructor(dbName = 'ProjectDB', version = 1) {
    this.dbName = dbName;
    this.version = version;
    this.db = null;
  }

  // 初始化数据库（支持配置存储和索引）
  async init(storesConfig = {
    projects: { keyPath: 'id' },
    documents: { keyPath: 'id' },
    todos: { 
      keyPath: 'id',
      indexes: [
        { name: 'projectId', keyPath: 'projectId' }
      ]
    }
  }) {
    return new Promise((resolve, reject) => {
      const request = indexedDB.open(this.dbName, this.version);
      
      request.onupgradeneeded = (event) => {
        const db = event.target.result;
        
        // 创建或升级对象存储
        for (const [storeName, config] of Object.entries(storesConfig)) {
          if (!db.objectStoreNames.contains(storeName)) {
            const store = db.createObjectStore(storeName, { keyPath: config.keyPath });
            
            // 创建索引
            if (config.indexes) {
              config.indexes.forEach(index => {
                store.createIndex(index.name, index.keyPath, index.options);
              });
            }
          }
        }
      };

      request.onsuccess = (event) => {
        this.db = event.target.result;
        resolve(this);
      };

      request.onerror = (event) => {
        reject(`IndexedDB error: ${event.target.error}`);
      };
    });
  }

  // 基础操作方法
  async add(storeName, data) {
    return this._execute('readwrite', storeName, store => store.add(data));
  }

  async get(storeName, id) {
    return this._execute('readonly', storeName, store => store.get(id));
  }

  async getAll(storeName) {
    return this._execute('readonly', storeName, store => store.getAll());
  }

  async update(storeName, data) {
    return this._execute('readwrite', storeName, store => store.put(data));
  }

  async delete(storeName, id) {
    return this._execute('readwrite', storeName, store => store.delete(id));
  }

  // 索引查询方法
  async getByIndex(storeName, indexName, key) {
    return this._execute('readonly', storeName, store => {
      const index = store.index(indexName);
      return index.get(key);
    });
  }

  async getAllByIndex(storeName, indexName, key) {
    return this._execute('readonly', storeName, store => {
      const index = store.index(indexName);
      return index.getAll(key);
    });
  }

  // 高级查询方法
  async getAllByIndexRange(storeName, indexName, range) {
    return this._execute('readonly', storeName, store => {
      const index = store.index(indexName);
      return index.getAll(range);
    });
  }

  // 私有方法
  async _execute(mode, storeName, operation) {
    if (!this.db) await this.init();
    
    return new Promise((resolve, reject) => {
      const tx = this.db.transaction(storeName, mode);
      const store = tx.objectStore(storeName);
      const request = operation(store);

      request.onsuccess = () => resolve(request.result);
      request.onerror = () => reject(request.error);
    });
  }
  /**
   * 导出整个数据库为JSON格式
   * @returns {Promise<{databaseName: string, version: number, data: Object}>}
   */
  async exportToJSON() {
    if (!this.db) await this.init();
    
    const exportData = {
      databaseName: this.dbName,
      version: this.version,
      timestamp: new Date().toISOString(),
      data: {}
    };

    // 获取所有对象存储名称
    const storeNames = Array.from(this.db.objectStoreNames);
    
    // 遍历每个存储并导出数据
    for (const storeName of storeNames) {
      try {
        exportData.data[storeName] = await this.getAll(storeName);
      } catch (error) {
        console.error(`导出存储 ${storeName} 失败:`, error);
        exportData.data[storeName] = [];
      }
    }

    return exportData;
  }

  /**
   * 导出为可下载的JSON文件
   * @param {string} [fileName] - 下载文件名
   * @returns {Promise<void>}
   */
  async exportAndDownload(fileName = `${this.dbName}_backup_${new Date().toISOString().slice(0,10)}.json`) {
    const data = await this.exportToJSON();
    this._downloadJSON(data, fileName);
  }

  // 私有方法：触发文件下载
  _downloadJSON(data, fileName) {
    const jsonStr = JSON.stringify(data, null, 2);
    const blob = new Blob([jsonStr], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    
    const a = document.createElement('a');
    a.href = url;
    a.download = fileName;
    document.body.appendChild(a);
    a.click();
    
    setTimeout(() => {
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
    }, 100);
  }
  /**
   * 批量添加数据
   */
  async addBulk(storeName, items) {
    return this._execute('readwrite', storeName, store => {
      const promises = items.map(item => {
        return new Promise((resolve, reject) => {
          const request = store.add(item);
          request.onsuccess = () => resolve();
          request.onerror = () => reject(request.error);
        });
      });
      return Promise.all(promises);
    });
  }

  /**
   * 清空存储
   */
  async clearStore(storeName) {
    return this._execute('readwrite', storeName, store => store.clear());
  }
}



// 单例模式导出
export default new IDB();